package com.dream.style.app.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;


/**
 * @Created by lincyu
 * @Time: 2018/11/13 15:55
 * @Decs: 类
 */
public class MyTabBar extends LinearLayout {
    public MyTabBar(Context context) {
        this(context,null);
    }
    public MyTabBar(Context context,  AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public MyTabBar(Context context,  AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }
    private void initView() {
    }

    /** 当前选中的选项卡 */
    private TabItem mCurrentTab;
    /** 选项卡字体和图标的颜色：普通状态 */
    private int mTabNormalColor = Color.GRAY;
    /** 选项卡字体和图标的颜色：选中状态 */
    private int mTabSelectedColor = Color.WHITE;
    /** 资源数据 */
    private String[] mTabNames;
    private int[] mTabIconsNormalids;
    private int[] mTabIconsSelectids;
    /** 选项卡中图片与文字的垂直间距 */
    int paddingBetweenTextAndIcon = dp2px(0);
    /** 选项卡图标的宽 */
    private int mIconWidth;
    /** 选项卡图标的高 */
    private int mIconHeight;
    /** 选项卡（子View） */
    private TabItem[] mTabs;
    /** MyTabBar 监听器 */
    private OnTabClickListener tabListener;
    /** 父类的监听器(包装一个子类的监听器对象) */
    private OnClickListener listener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            setTabIsOnClick(position);
            if (tabListener != null){
                tabListener.onTabOnClick(position);
            }
        }
    };

    // 设置当前被选中的位置
    private void setTabIsOnClick(int position) {
        mCurrentTab.setTabSelected(false);
        mCurrentTab = mTabs[position];
        mCurrentTab.setTabSelected(true);
    }

    /**
     * 这里要记住，只要是集体的行为，应该让 MyTabBar 去管理，例如
     * 间隔，图标大小，以及文本图片                   （更新）
     * 而那些单个的，可以让 TabItem 去管控 或者更新视图，例如
     * 图标背景色，文本颜色                           （更新）
     */
    // 我只是一个快乐的搬运工
    public MyTabBar setTabBackgroundColor(int color) {
        super.setBackgroundColor(color);
        return this;
    }
    public MyTabBar setTabPaddingTextToIcon(int padding) {
        paddingBetweenTextAndIcon = dp2px(padding);
        if (mTabs != null) {
            for (int i = 0; i < mTabs.length; i++) {
                mTabs[i].setPaddingBetweenTextAndIcon(padding);
            }
            invalidate();
        }
        return this;
    }
    public MyTabBar setTabColorNormal(int color) {
        this.mTabNormalColor = color;
        return this;
    }
    public MyTabBar setTabColorSelected(int color) {
        this.mTabSelectedColor = color;
        return this;
    }
    public MyTabBar setTabTitle(String[] mTabNames){
        this.mTabNames = mTabNames;
        return this;
    }
    public MyTabBar setTabNormalIconId(int[] mTabIconsNormal){
        this.mTabIconsNormalids = mTabIconsNormal;
        return this;
    }
    public MyTabBar setTabSelectIconId(int[] mTabIconsSelect){
        this.mTabIconsSelectids = mTabIconsSelect;
        return this;
    }
    public MyTabBar setTabIconSize(int width, int height) {
        mIconWidth = dp2px(width);
        mIconHeight = dp2px(height);
        if (mTabs != null){
            for(int i = 0; i<mTabs.length; i++){
                mTabs[i].setIconSize(mIconWidth, mIconHeight);
            }
            invalidate();
        }
        return this;
    }
    public MyTabBar setOnTabClickLlistener(OnTabClickListener tabListener){
        this.tabListener = tabListener;
        return this;
    }
    // 提交设置，生成视图View
    public void commit() {
        // 清空旧的视图
        removeAllViews();
        // 添加新的视图
        addTabView();
        // 默认选中第一个标签
        mCurrentTab = mTabs[0];
        mCurrentTab.setTabSelected(true);
    }
    private void addTabView() {
        // 布局参数
        LayoutParams param = new LayoutParams(0, LayoutParams.MATCH_PARENT);
        param.weight = 1;		// 使用权重，表示四个选项卡会平分屏幕的宽度
        mTabs = new TabItem[mTabNames.length];

        // 循环生成子View对象
        for (int i=0; i<mTabs.length; i++){
            TabItem tab = new TabItem(getContext());

            mTabs[i] = tab;
            // 标题
            String iconName = mTabNames != null ? mTabNames[i] : "Null";
            // 选中图标
            int iconSelect = 0;
            if (mTabIconsSelectids!=null) {
                iconSelect = mTabIconsSelectids.length > 0 ? mTabIconsSelectids[i] : 0;
            }
//            int iconNormal = mTabIconsNormalids != null ? mTabIconsNormalids[i] : 0;
            int padding = dp2px(5);
            try {
                tab.setTabTag(i)
                        .setTabNormalColor(mTabNormalColor)
                        .setTabSelectedColor(mTabSelectedColor)
                        .setPaddingBetweenTextAndIcon(paddingBetweenTextAndIcon)
                        .setIconSize(mIconWidth, mIconHeight)
                        .setTabPadding(0, padding, 0, padding)
                        .setTextAndIcon(iconName, mTabIconsNormalids[i],iconSelect)
                        .setTabOnClickListener(listener)
                        .commit();
            } catch (Exception e) {
                e.printStackTrace();
            }
            addView(tab, param);
        }
    }
    // 计算转换
    public int dp2px(int dp){
        return (int) (getResources().getDisplayMetrics().scaledDensity * dp + 0.5f);
    }
    // 选项卡监听器
    public interface OnTabClickListener{
        void onTabOnClick(int position);
    }
    // 内部类：选项卡对象
    private static class TabItem extends View {

        public TabItem(Context context) {
            this(context,null,0);
        }
        public TabItem(Context context, AttributeSet attrs) {
            this(context, attrs,0);
        }
        public TabItem(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            initView();
        }

        /** 绘制文本的画笔 */
        private Paint mTextPaint = new Paint();
        /** 选项卡字体大小: 默认为12sp */
        private int mTabTextSize = dp2px(12);
        /** 文字的绘制区域 */
        private Rect mTextBound = new Rect();
        /** 图标的绘制区域 */
        private Rect mIconBound = new Rect();

        // 初始化任务（画笔）
        private void initView() {
            mTextPaint.setAntiAlias(true);      // 去锯齿
            mTextPaint.setTextSize(mTabTextSize);
            mTextPaint.setColor(mTabColorNormal);
//            mTextPaint.setTextAlign(Paint.Align.CENTER); // 文本居中
//            mTextPaint.getTextBounds(mTabName, 0, mTabName.length(), mTextBound);
        }
        // 公用计算
        public int dp2px(int dp){
            return (int) (getResources().getDisplayMetrics().scaledDensity * dp + 0.5f);
        }
        // 在测量控件里头初始化图标绘制区域

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            Log.e("","onMeasure");
            initTabDrawArea();
        }
        // 设置图片绘制区域
        private void initTabDrawArea() {
            // 图域左边 = （视图的宽 - 图片的宽）/ 2
            int left = getMeasuredWidth()/2 - mIconWidth/2;
            // 图域顶部 = （视图的高 - 图高 - 文本高）/ 2
            int top = getMeasuredHeight()/2 - (mTextBound.height()+mIconHeight)/2;
//            LogUtils.e(left,top,left+mIconWidth,top+mIconHeight);
            mIconBound.left = left;
            mIconBound.top = top;
            mIconBound.right = left + mIconWidth;
            mIconBound.bottom = top + mIconHeight;
        }

        // 画的是当个文本
        @Override
        protected void onDraw(Canvas canvas) {
            // 绘制红点
            // ...
            // 绘制未读取条数
            // ...

            // 绘制tab原文本(255：不透明)
            drawText(canvas,mTabColorNormal,255);
            // 绘制渐变色的文本(范围大于或等于)
            int alpha = (int) Math.ceil(255 * mAlphaPercent);
//            drawText(canvas, mTabColorSelected, alpha);
            drawText(canvas, mTabColorSelected, alpha);

            // 只使用一张图片实现选项卡的普通和高亮两种状态
            if (mTabIconSelected == null) {
                // 绘制tab图标
                canvas.drawBitmap(mTabIconNormal, null, mIconBound, null);
                // 内存去准备mBitmap , setAlpha , 纯色 ，xfermode
//                mGradientBitmap = createGradientBitmap(alpha, mTabColorSelected);
//
//                // 绘制渐变色的图标
//                canvas.drawBitmap(mGradientBitmap, 0, 0, null);

            } else {	//使用两张图片实现选项卡的普通和高亮两种状态
                if (alpha == 0) {
//                    LogUtils.e("透明，非选中、非高亮");
                    canvas.drawBitmap(mTabIconNormal, null, mIconBound, null);
                } else {
//                    LogUtils.e("不透明，被选中，高亮");
                    canvas.drawBitmap(mTabIconSelected, null, mIconBound, null);
                }
            }
        }

        // 写文本
        private void drawText(Canvas canvas, int color, int alpha) {
            mTextPaint.setColor(color);
            mTextPaint.setAlpha(alpha);
            int x = (getMeasuredWidth() - mTextBound.width()) / 2;
            int y = mIconBound.bottom + mTextBound.height() + paddingBetweenTextAndIcon;
            canvas.drawText(mTabName,x,y,mTextPaint);
        }

        /** 选项卡图标的宽 */
        private int mIconWidth;
        /** 选项卡图标的高 */
        private int mIconHeight;
        /** 选项卡中图片与文字的垂直间距 */
        private int paddingBetweenTextAndIcon = dp2px(0);
        /** tab显示的文本 */
        private String mTabName = "Tab标题";
        /** 选项卡图标: 普通状态。也可以只使用一张图标，选中时会对它进行着色 */
        private Bitmap mTabIconNormal;
        /** 选项卡图标: 选中状态。也可以只使用一张图标，选中时会对它进行着色 */
        private Bitmap mTabIconSelected;
        /** 选项卡字体和图标的颜色：普通状态 */
        private int mTabColorNormal = Color.GRAY;
        /** 选项卡字体和图标的颜色：选中状态 */
        private int mTabColorSelected = Color.BLACK;
        TabItem setIconSize(int iconWidth, int iconHeight) {
            this.mIconWidth = iconWidth;
            this.mIconHeight = iconHeight;
            return this;
        }
        TabItem setPaddingBetweenTextAndIcon(int padding) {
            this.paddingBetweenTextAndIcon = padding;
            return this;
        }
        TabItem setTextAndIcon(String tabName, int iconNormal, int iconSelect) {
            this.mTabName = tabName;
            this.mTabIconNormal = BitmapFactory.decodeResource(getResources(),iconNormal);
            if (iconSelect>0){  // 必须大于0，没有大于0说明没有设置选择图片
                this.mTabIconSelected = BitmapFactory.decodeResource(getResources(),iconSelect);
            }
            mTextPaint.getTextBounds(mTabName,0,mTabName.length(),mTextBound);
//            initTabDrawArea();
            return this;
        }
        TabItem setTabNormalColor(int mTabColorNormal) {
            this.mTabColorNormal = mTabColorNormal;
            return this;
        }
        TabItem setTabSelectedColor(int mTabColorSelected) {
            this.mTabColorSelected = mTabColorSelected;
            return this;
        }
        TabItem setTabPadding(int l, int t, int r, int b){
            super.setPadding(l,t,r,b);
            return this;
        }
        TabItem setTabTag(int i){
            super.setTag(i);
            return this;
        }
        TabItem setTabOnClickListener(View.OnClickListener l) {
            super.setOnClickListener(l);
            return this;
        }
        void commit() {
            invalidate();
        }

        // 标记是否被点击          true：1：不透明，      false：0：透明
        public void setTabSelected(boolean isSelect) {
            setTabAlpha(isSelect ? 1 : 0);
        }
        // 滑动时图标的透明度
        private float mAlphaPercent;
        private void setTabAlpha(float alpha){
            if (mTabIconSelected != null){
                // 如果使用了两张图片实现普通和高亮的效果，
                // 则禁用颜色渐变的功能；
//                if (alpha!=0  || alpha!=1){
//                    return;
//                }
                this.mAlphaPercent = alpha;
                invalidate();
            }
        }

    }//end TabItem





}
